//
//  HMAccessory.swift
//  home
//
//  Created by Yun Zeng on 2018/11/25.
//  Copyright © 2018 Yun Zeng. All rights reserved.
//

import Foundation

// 支持配件的类型
enum HMAccessoryType: Int, Codable {
    case unknown = 0
    case homemaster = 1
    case homemasterV2 = 2
    case outlet = 3
    case `switch` = 4
    case contactSensor = 6
    case htSensor = 7
    case colorLight = 8
    case temperatureColorLight = 9
    case motionSensor = 10
}

//
// Accessory 配件，为一个独立的设备，
//    如一个HomeMaster网关、Zigbee三路开关、Zigbee温湿度器、Zigbee调光灯、Zigbee人体感应器等
// 一个配件可以包含多个服务，如一个HomeMaster网关包含Zigbee协调器、温湿度、光线、空调遥控器等
// 每个配件都有自己的位置属性，如将一个三路开关移动到另外一个房间，下面从属的三个开关服务也会移动至另外一个房间
// 每一个配件都拥有唯一的配件ID
//
class HMAccessory: Codable {
    
    // 指向设备所属的容器
    var container: HMContainer?
    
    // 配件描述
    var id: String
    var type: Int
    var services: [HMService]
    var reachable: Bool = true {
        didSet {
            if reachable == false {
                for service in self.services {
                    service.needUpdate(state: .offline)
                }
            }
        }
    }
    
    private enum CodingKeys: String, CodingKey {
        case id = "aid"
        case type
        case services
    }
    
    init(id: String, type: HMAccessoryType, services: [HMService]) {
        self.id = id
        self.type = type.rawValue
        self.services = services
    }
    
    func findService(sid: Int) -> HMService? {
        for s in self.services {
            if s.id == sid {
                return s
            }
        }
        return nil
    }
    
}

// 调试输出打印
extension HMAccessory: CustomStringConvertible {
    var description: String {
        let data = try! JSONEncoder().encode(self)
        return String(data: data, encoding: .utf8)!
    }
}



